package com.ytzq.web.action;

import com.ytzq.base.constants.LOG_TYPE;
import com.ytzq.base.helper.StringHelper;
import com.ytzq.base.log.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.RequestDispatcher;

import org.apache.commons.beanutils.MethodUtils;

import java.io.IOException;

/**
 * Servlet基础类：用来地址转发
 * @author 门士松  20121228
 * @version 1.0
 * @since
 */
@SuppressWarnings("serial")
public class ForwardAction extends HttpServlet{
	
	private Logger logger = Logger.getLogger(this.getClass());
    private ServletConfig servletConfig = null;

    @Override
    public void init(ServletConfig servletConfig){
        this.servletConfig = servletConfig;
    }
    /**
     * Service主方法
     * @param request
     * @param response
     * @throws javax.servlet.ServletException
     * @throws java.io.IOException
     */
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	try{
            logger.debug(LOG_TYPE.BUSINESS,"进入servlet跳转方法...");
            String path = "";
            String uri = request.getRequestURI();
            logger.debug(LOG_TYPE.SYSTEM,"请求的action地址" ,uri);
            int pos = uri.indexOf("/action/", 0);
            path = uri.substring(pos + 8);
            logger.debug(LOG_TYPE.SYSTEM,"转换后的地址" ,path);
            if (StringHelper.isEmpty(path)){
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }else{
            	//若路径中存在".",则肯定是错误的class名称
                if (path.indexOf(".") > 0) {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
	            //根据路径生成相应的Action对象
	            String className = "com.ytzq." + path.replace("/", ".");
	            logger.info(LOG_TYPE.BUSINESS,"通过反射实例化对应的Action，className为:"+className);      
	        	Action action = (Action) Class.forName(className).newInstance();
	            logger.info(LOG_TYPE.SYSTEM,"实例化成功action为" ,action.toString());
	            if (action != null && action instanceof Action){
	                logger.debug(LOG_TYPE.BUSINESS,"实例化成功，执行默认方法...");  
	                //初始化
	            	action.init(request,response);
	                String function = request.getParameter("function");
	                String method = (function==null||function.length() == 0) ? "default" : function;
	                method = "do" + method.substring(0, 1).toUpperCase() + method.substring(1);
	                //在进入相应的function对应的方法前，先调用before方法
	            	logger.debug(LOG_TYPE.BUSINESS,"进入function方法前执行before方法...");
	            	action.before(request,response);
	            	logger.debug(LOG_TYPE.BUSINESS,"进入function方法...");
	                ActionResult actionResult = (ActionResult) MethodUtils.invokeMethod(action, method, null);
	                //在调用相应的方法后，再调用after
	            	logger.debug(LOG_TYPE.BUSINESS,"进入function方法后执行after方法...");
	            	action.after(request,response);
	                logger.debug(LOG_TYPE.BUSINESS,"执行action完成，进入跳转...");    
	                if (actionResult != null){
	                    if (actionResult.isDispatch()){
	                    	//容器内跳转(FORWORD)
	                        ServletContext context = servletConfig.getServletContext();
	                        RequestDispatcher dispatcher = context.getRequestDispatcher(actionResult.getPage());
	                        dispatcher.forward(request, response);
	                    //容器外跳转(Redirect)    
	                    }else{
	                        response.sendRedirect(request.getContextPath() + actionResult.getPage());
	                    }
	                }
	            }else{
	                response.sendError(HttpServletResponse.SC_NOT_FOUND);
	            }
	            logger.debug(LOG_TYPE.BUSINESS,"完成servlet跳转并返回...");
            }
        }catch (ClassNotFoundException e){
        	logger.error(LOG_TYPE.SYSTEM, e);
        	response.sendError(HttpServletResponse.SC_NOT_FOUND );
        }catch (Exception ex){
        	logger.error(LOG_TYPE.SYSTEM, ex);
        	response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
        }
    }
}
